package kr.co.redbean.main 
{
	import com.greensock.TweenLite;
	import com.greensock.easing.Expo;
	
	import flash.display.DisplayObject;
	import flash.display.GradientType;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.FullScreenEvent;
	import flash.events.IOErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.System;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	import flashx.textLayout.formats.BackgroundColor;
	
	import kr.co.redbean.events.ForegroundLoaderEvent;
	import kr.co.redbean.events.MenuEvent;
	import kr.co.redbean.frame.*;
	import kr.co.redbean.loader.BackgroundLoader;
	import kr.co.redbean.loader.ForegroundLoader;
	import kr.co.redbean.store.IObjectInfo;
	import kr.co.redbean.store.ObjectStore;
	
	import mx.events.FlexEvent;
	import mx.events.ModuleEvent;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;
	import mx.styles.StyleManager;
	
	import org.osmf.events.LoaderEvent;
	
	[Frame(factoryClass="kr.co.redbean.main.SJ_Preloader")]
	[SWF(backgroundColor="#ffffff")]
	public class Main extends Sprite
	{
		private var rootAD:ApplicationDomain;
		private var mainAD:ApplicationDomain;
		private var backgroundLoader:BackgroundLoader;
		private var foregroundLoader:ForegroundLoader;
		
		private var mainFrame:IMainFrame;
		private var memberMenu:IMainFrame;
		private var mainMenu:IMainFrame;
		
		private var menuFrame:IFrame;
		private var memberFrame:IFrame;
		private var popupFrame:IFrame;
		
		
		public function Main() {
			mainFrame = new Frame;
			memberMenu = new MemberMenu;
			mainMenu = new MainMenu;
			
			menuFrame = new MenuFrame;
			memberFrame = new MemberFrame;
			popupFrame = new PopupFrame;
			
			backgroundLoader = new BackgroundLoader;
			foregroundLoader = new ForegroundLoader;
			
			addEventListener(Event.ADDED_TO_STAGE,ADDED_TO_STAGE);
		}
		private function ADDED_TO_STAGE( $e:Event ):void {
			removeEventListener(Event.ADDED_TO_STAGE,ADDED_TO_STAGE);
			initialize();
			runApp();
		}
		
		private function initialize():void {
			// todo: 팝업메뉴 포커스, 모달 관리하는 global instance 제작할것
			globalSetting();
			loadFonts();
			loadMainFrame();
			loadModulesBackground();
			runApp();
		}
		
		private function loadFonts():void {
			// font loading
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
			loader.load(new URLRequest("embedFont.swf"));
			
			function completeHandler(event:Event):void {
				var embedFont:Class = event.target.applicationDomain.getDefinition("embedFont") as Class;
				Font.registerFont(embedFont.font1);
			}
		}
		
		private function runApp():void {
			dispatchEvent(new MenuEvent(MenuEvent.MENU_CLICK, 'home'));
		}
		
		private function loadModulesBackground():void {
			// 백그라운드에서 로딩할 자원 설정 ->나중에 xml로 뺄것(페이지뷰를 비교해 높은 빈도를 먼저 로딩하도록 설정 - php로 제작)
			var os:ObjectStore;
			os = ObjectStore.getInstance();
			os.setObjectProxyList(<modules>
									<module name="home" priority="1" domain="menu" />
									<module name="magazine" priority="11" domain="menu" />
									<module name="clothing" priority="10" domain="menu" />
									<module name="accessories" priority="12" domain="menu" />
									<module name="blogs" priority="13" domain="menu" />
									<module name="help" priority="14" domain="menu" />
									<module name="login" priority="2" domain="member">
										<properties name="width" value="200" />
										<properties name="height" value="150" />
									</module>
									<module name="join" priority="3" domain="member">
										<properties name="width" value="400" />
										<properties name="height" value="300" />
									</module>
									<module name="shoppingbag" priority="4" domain="popup">
										<properties name="width" value="400" />
										<properties name="height" value="300" />
										<properties name="x" value="300" />
										<properties name="y" value="300" />
									</module>
									
								  </modules>);
			
			backgroundLoader.load();
		}
		
		
		private function globalSetting():void {
			// default stage setting
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.frameRate = 60;
			stage.showDefaultContextMenu = false;
			//stage.loaderInfo.parameters; // flashvar 값
			stage.stageFocusRect = false;
			stage.tabChildren = false;

			// initialize stage event listeners
			stage.addEventListener(Event.ACTIVATE, ACTIVATE);
			stage.addEventListener(Event.DEACTIVATE, DEACTIVATE);
			stage.addEventListener(Event.RESIZE, RESIZE);
			stage.addEventListener(FocusEvent.FOCUS_IN, FOCUS_IN);
			stage.addEventListener(FocusEvent.FOCUS_OUT, FOCUS_OUT);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, KEY_DOWN);
			stage.addEventListener(KeyboardEvent.KEY_UP, KEY_UP);
			stage.addEventListener(MenuEvent.MENU_CLICK, MENU_CLICK);
			foregroundLoader.addEventListener(ForegroundLoaderEvent.SETUP, LOADER_SETUP);
			foregroundLoader.addEventListener(ForegroundLoaderEvent.PROGRESS, LOADER_PROGRESS);
			foregroundLoader.addEventListener(ForegroundLoaderEvent.COMPLETE, LOADER_COMPLETE);
			
			System.useCodePage = false;
		}
		
		private function loadMainFrame():void {
			mainFrame.alpha = 0;
			memberMenu.alpha = 0;
			mainMenu.alpha = 0;
			
			addChild(mainFrame as DisplayObject);
			addChild(memberMenu as DisplayObject);
			addChild(mainMenu as DisplayObject);
			addChild(menuFrame as DisplayObject);
			addChild(memberFrame as DisplayObject);
			addChild(popupFrame as DisplayObject);
			
			TweenLite.to(mainFrame, 2, { alpha: 1, ease:Expo.easeOut });
			TweenLite.to(memberMenu, 2, { alpha: 1, ease:Expo.easeOut });
			TweenLite.to(mainMenu, 2, { alpha: 1, ease:Expo.easeOut });
		}
		
		private function getFrameByDomainName(domain:String):IFrame {
			var rtn:IFrame;
			
			switch(domain) {
				case 'menu' : rtn = menuFrame;break;
				case 'member' : rtn = memberFrame;break;
				case 'popup' : rtn = popupFrame;break;
			}
			return rtn;
		} 
		// handlers
		
		private function MENU_CLICK($e:MenuEvent):void {
			var objectStore:ObjectStore;
			var menu:IObjectInfo;
			var frame:IFrame;
			
			objectStore = ObjectStore.getInstance();
			menu = objectStore.getObjectByName($e.menu);
			frame = getFrameByDomainName(menu.domain);
			
			// 중복팝업 방지
			// 중복팝업이 금지되있을 경우 close시 반드시 frame.currentFocus를 null로 초기화 해줄것 
			if(frame.currentFocus === $e.menu || (menu.domain === 'member' && frame.currentFocus !== null)) return;
			frame.currentFocus = $e.menu;
			
			foregroundLoader.load(menu);
		}
		
		private function LOADER_SETUP($e:ForegroundLoaderEvent):void { trace($e.loadProxy.domain);
			var _target:IFrame;
			_target = getFrameByDomainName($e.loadProxy.domain);
			_target.doSetupMotion($e.loadProxy);
		}
		
		private function LOADER_PROGRESS($e:ForegroundLoaderEvent):void { trace($e.loadProxy.domain, $e.bytesLoaded, $e.bytesTotal);
			var _target:IFrame;
			_target = getFrameByDomainName($e.loadProxy.domain);
			_target.doProgressMotion($e.bytesLoaded, $e.bytesTotal);
		}
		
		private function LOADER_COMPLETE($e:ForegroundLoaderEvent):void { trace($e.loadProxy.domain);
			var _target:IFrame;
			_target = getFrameByDomainName($e.loadProxy.domain);
			_target.addObject($e.loadProxy.objectProxy as DisplayObject);
			_target.doCompleteMotion($e.loadProxy.objectProxy);
		}
			
		static private function ACTIVATE($e:Event):void {
			
		} 
		static private function DEACTIVATE($e:Event):void {
			
		}
		private function RESIZE($e:Event):void {
			mainFrame.setPlacement();
			menuFrame.setPlacement();
			popupFrame.setPlacement();
			memberMenu.setPlacement();
			mainMenu.setPlacement();
		}
		static private function FOCUS_IN($e:FocusEvent):void {
			
		}
		static private function FOCUS_OUT($e:FocusEvent):void {
			
		}
		static private function KEY_DOWN($e:KeyboardEvent):void {
			$e.stopPropagation();
		}
		static private function KEY_UP($e:KeyboardEvent):void {
			$e.stopPropagation();
		}
	}
}